import React from 'react';
import '@ant-design/compatible/assets/index.css';
import { Input, message, Button, Card, Select, InputNumber, Table, Form, Radio } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import router from 'umi/router';
import * as R from 'ramda';
import { FormInstance } from 'antd/lib/form';
import { getDictOptionsByCode } from '@/support/common';

const transferOption = (arrayData = [], keyValue = ['value', 'label']) =>
  R.map(
    (item:any) => <Select.Option key={item[keyValue[0]]}>{item[keyValue[1]]}</Select.Option>,
    arrayData,
  );
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 4 },
    sm: { span: 14 },
  },
};
const strategyList =  [{dataKey: 1, dataValue: '需购买且赠送'},{dataKey: 2, dataValue: '需购买且试用'},{dataKey: 3, dataValue: '需购买但不赠送不试用'},
  {dataKey: 4, dataValue: '不需要购买'},];
let tableData : any[];//蓝牙策略列表数据源

// @Form.create()
@connect((state: any) => ({
  bluetoothConfiguration: state.bluetoothConfiguration,
  loading: state.loading.models['bluetoothConfiguration'],
   menu: state.menu,
}))
export default class bluetoothConfigurationAdd extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      seriesOptions: [], // 车系列表
      nameOptions: [], //车型组列表
      buttonLoading: false,
      strategyConfigList: [],
    };
  }

  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.any,
  };
  formRef = React.createRef<FormInstance>();
  componentDidMount() {
    // 获取车系数据
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'bluetoothConfiguration/getDataWithRes',
      payload: { url: '/msdevice/base/vehicle/series/list' },
      callback: (e: any) => {
        if (e.data) {
          this.setState({
            seriesOptions: e.data.map(e => ({
              seriesName: e.seriesName,
              seriesCode: e.seriesCode,
            })),
          });
        }
      },
    });
  }
  componentWillReceiveProps() {
    if (this.props.location && this.props.location.state) {
      const { formData, giveType } = this.props.location.state;
      if(JSON.stringify(formData) !== "{}" && (formData?.strategyConfigList)){
        tableData = giveType?.map((item:any, index:any) =>{
         const data = this.getstrategy(item.key, formData.strategyConfigList);
         return {
           key: index+1,
           id: this.getId(item.giveType, formData.strategyConfigList),
           giveType: item.giveType,
           strategy: this.getstrategy(item.giveType, formData.strategyConfigList),
           days: this.getdays(item.giveType, formData.strategyConfigList),
           giveTypeName: item.giveTypeName,
           inputDisabled: data&&(data == 3 || data == 4) ? true :false
         }
       })
       this.setState({ strategyConfigList: tableData });
     }
   else{
    if(this.state.strategyConfigList.length > 0){
      const {strategyConfigList}=this.state;
      this.setState({ strategyConfigList: [...strategyConfigList] });
    }else{
      tableData = giveType?.map((item:any, index:any) =>{
        return {
          key: index+1,
          giveType: item.giveType,
          strategy: '',
          days: '',
          giveTypeName: item.giveTypeName,
          inputDisabled: false
        }
      })
      this.setState({ strategyConfigList: tableData });
    }
   }
  //  this.setState({ strategyConfigList: tableData });
    } 
  }
  getstrategy=(giveType:any, arr:any)=> {//通过giveType查询出已配置的strategy
    return arr.find((item:any) => item.giveType ===giveType)?.strategy  ? arr.find((item:any) => item.giveType ===giveType)?.strategy : ''
  }
   getdays=(giveType:any, arr:any)=> {//通过giveType查询出已配置的days
    return arr.find((item:any) => item.giveType ===giveType)?.days  ? arr.find((item:any) => item.giveType ===giveType)?.days : ''
  }
   getId=(giveType:any, arr:any)=> {//通过giveType查询出已配置的id
    return arr.find((item:any) => item.giveType ===giveType)?.id  ? arr.find((item:any) => item.giveType ===giveType)?.id : ''
  }
  handleCancel = () => {
    if (this.props.location && this.props.location.state) {
      const { pageObj, formValues, backUrl } = this.props.location.state;
      router.push({ pathname: backUrl, state: { pageObj: pageObj, formValues } });
    } else {
      router.push({ pathname: '/remoteConfiguration/bluetoothConfiguration' });
    }
    this.formRef.current?.resetFields();
    this.setState({strategyConfigList: [] });
    tableData = [];
  };
  // 通过车系查询车型组信息
  onSelect = (value: any) => {
    if (value) {
      const key = value.key;
      this.props.dispatch({
        type: 'bluetoothConfiguration/postData',
        payload: { url: '/vehicle/group/findBySeriesCode', seriesCode: key },
        callback: (e: any) => {
          if (e.data) {
            this.setState({
              nameOptions: e.data.map(e => ({
                name: e.name,
                typeGroupCode: e.code,
              })),
            });
          } else {
            this.setState({
              nameOptions: '',
            });
          }
        },
      });
    } else {
      this.setState({
        nameOptions: '',
      });
    }
    // 重新选取车系，清空车型组所选内容
    this.formRef.current?.setFieldsValue({
      typeGroupCode: ''
    })
  };

  ok = (values: any) => {
    const { strategyConfigList } = this.state;
    let ifErr = false;//数据是否正常标志，默认为正常
      for (var i = 0; i < strategyConfigList.length; i++) {
        var item = strategyConfigList[i];
        if (item.strategy == '') {
          message.warning('请选择'+item.giveTypeName+'的运营策略！');
          ifErr = true;
        }
        if ((item.strategy == 1  || item.strategy == 2)&& item.days == '') {
          message.warning('请填写'+item.giveTypeName+'的赠送时长！');
          ifErr = true;
        } 
      }
      if (ifErr) {
        return;
      }

      let url = '/bluetoothkey/tas/config/save';

      this.setState({ buttonLoading: true });
     
      const params = {};
      var arr = JSON.parse(JSON.stringify(strategyConfigList))
      for (const key in arr) {
        // 删除属性
        delete arr[key].key;
        delete arr[key].giveTypeName;
        delete arr[key].inputDisabled;
        if(arr[key].id == ''){
          delete arr[key].id;
          break;
        }
     }
      params['seriesCode']= values.seriesCode.key;
      params['typeGroupCode']= values.typeGroupCode.key;
      params['typeGroupName']= values.typeGroupCode.label;
      params['remark']= values.remark;
      params['strategyConfigList']= arr;
      params['bluetoothProvider']= values.bluetoothProvider;
      params['isBluetoothConfigSend'] = values.isBluetoothConfigSend;
      this.props.dispatch({
        type: 'bluetoothConfiguration/postObjWithRes',
        payload: { url: url, ...params },
        callback: (response:any) => {
          if (response.statusCode === "0") {
            message.success("操作成功！");
            this.handleCancel();
          } else {
            // message.error(response.statusMessage);
          }
          this.setState({ buttonLoading: false });
        }
      });
}
  render() {
    const { buttonLoading, seriesOptions, nameOptions, strategyConfigList } = this.state;
    const bluetoothProvider = getDictOptionsByCode(this.context.dicData, 'bluetoothProvider');
    const  getRowByKey=(key: any) =>{
      return (strategyConfigList.length >0 ? strategyConfigList : tableData).filter(item => item.key === key)[0];
    }
    const handleStrategyChange=(value:any, record:any)=>{//获取选中的值及当前行列表的信息
      const newData = strategyConfigList.length >0 ? [...strategyConfigList] : tableData;
      const target = getRowByKey(record.key);
      if (target) {
        target.strategy = parseInt(value);
        if(value == 3 || value ==4){
          target.inputDisabled = true;
          target.days = '';
        }else{
          target.inputDisabled = false
        }
        this.setState({ strategyConfigList: newData });
      }
      
    }
    const handleDaysChange=(value:any, record:any)=>{//获取选中的值及当前行列表的信息
    const newData = strategyConfigList.length >0 ? [...strategyConfigList] : tableData;
    const  target = getRowByKey(record.key);
    if (target) {
      if(value){
      target.days = parseInt(value);
      }else{
      target.days = '';
      }
      this.setState({ strategyConfigList: newData });
    }
    }
    const columns = [{
      title: '蓝牙服务类型',
      dataIndex: 'giveTypeName',
    }, {
      title: '运营策略',
      dataIndex: 'strategy',
      render: (text:any, record:any) => {
          return (
            <Select
              getPopupContainer={triggerNode => triggerNode.parentNode}
              onChange={(value, e) => handleStrategyChange(value, record)}
              placeholder="请选择运营策略"
              defaultValue={(record.strategy)?.toString()}
            >
              {strategyList.map(d => <Select.Option key={d.dataKey}>{d.dataValue}</Select.Option>)}
            </Select>
          );
      },
    }, {
      title: '赠送/试用时长（天）',
      dataIndex: 'days',
      key: 'days',
      render: (text:any, record:any) => {
        if(record.inputDisabled){
          return (
            <InputNumber
              onChange={(value:any)=>{handleDaysChange(value, record)}}
              precision={0}
              min={1}
              disabled
              value={''}
            />
          );
        }else{
          return (
            <InputNumber
              onChange={(value: any) => handleDaysChange(value, record)}
              placeholder="请输入"
              precision={0}
              min={1}
              defaultValue={record.days}
            />
          );
        }
        }
    }, ];
    return (
      <div>
        <Card bordered={false}>
          <Form layout="horizontal" ref={this.formRef} onFinish={this.ok}>
            <Form.Item {...formItemLayout} 
            name="seriesCode" 
            label="车系"
             required
             rules={[{ required: true, message: '请选择车系' }]}>
              
                <Select placeholder="请选择" onChange={this.onSelect} labelInValue={true}>
                  {transferOption(seriesOptions, ['seriesCode', 'seriesName'])}
                </Select>
              
            </Form.Item>
            <Form.Item {...formItemLayout} 
            name="typeGroupCode" 
            label="车型组"
             required
             rules={[{ required: true, message: '请选择车型组' }]}
            >
                <Select placeholder="请选择" labelInValue={true}>
                  {transferOption(nameOptions, ['typeGroupCode', 'name'])}
                </Select>
            </Form.Item>
            <Form.Item {...formItemLayout} 
                name="bluetoothProvider" 
                label="蓝牙钥匙供应商"
                 required
                 rules={[{ required: true, message: '请选择蓝牙钥匙供应商' }]}
              >
                <Select placeholder="请选择"  options={bluetoothProvider}>
                </Select>
            </Form.Item>
            <Form.Item {...formItemLayout} 
                name="isBluetoothConfigSend" 
                label="蓝牙服务配置下发"
                 required
                 rules={[{ required: true, message: '请选择蓝牙服务配置下发' }]}
              >
               <Radio.Group>
                <Radio value={1}>是</Radio>
                <Radio value={0}>否</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
                  label=""
                >
                  <Table
                    bordered={true}
                    rowKey={record => record.key}
                    columns={columns}
                    dataSource={this.state.strategyConfigList.length>0? this.state.strategyConfigList : tableData}
                    pagination={false}
                      />
                </Form.Item>
                <Form.Item
                  {...formItemLayout}
                  label="备注"
                  name="remark" 
                >
                      <TextArea  placeholder="请输入备注"/>
                </Form.Item>           
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={buttonLoading}
              >
                {' '}
                保存{' '}
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={this.handleCancel}>
                {' '}
                取消{' '}
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
